import { ZodError, z } from "zod";
import SuperJSON from "superjson";
import useDeTokenSetCookie from "~/server/utils/handlerDeTokenSetCookie";

// 封装: 包外 过程
const registerSchema = z.object({
  email: z.string().trim().min(3, "邮箱格式错误").email("错误的邮箱格式"),
  password: z.string().min(6, "密码过短").max(20, "密码过长"),
});

export default defineEventHandler(async (event) => {
  const storage = useStorage("data");
  // read Body
  const body = await readBody<ReqPayLoad<UserLoginType>>(event).catch(() => {
    throw createError({
      status: 400,
      message: "An error occurred in register",
    });
  });
  console.log("login res body", body);

  try {
    registerSchema.parse(body.data);
  }
  catch (e: any) {
    if (e instanceof ZodError) {
      throw createError({
        status: 400,
        data: {
          message: e.errors[0].message,
          code: e.errors[0].code,
          path: e.errors[0].path,
        },
      });
    }
    else {
      throw createError({
        status: 400,
        data: {
          message: "参数错误",
          code: "参数错误",
          path: "",
        },
      });
    }
  }

  useDeTokenSetCookie(body.data.email, event);

  const userData: ReqPayLoad<UserType> = {
    data: {
      id: 1, // 0 为未登录
      email: body.data.email,
      phone: "",
      password: "",
      nickname: body.data.email.split("@")[0],
      // avatar: "",//暂时砍掉
      sex: "未知",
      desc: "",
      status: 1, // 0 下线 1 启用
      created_time: Date.now(),
      updated_time: Date.now(),
    },
  };
  storage.setItem("user", SuperJSON.stringify(userData));
  return userData;
});
